﻿<form id="frmBXJGShopProduct" class="frm-container">
    <input type="hidden" name="id" value="0" />
    <table class="frm-box">
        <tr>
            <th>名称</th>
            <td colspan="5">
                <input name="title" class="easyui-textbox" data-options="width:815, required:true, validType:'length[1,100]',prompt:'简短、准确的商品标题...'" />
            </td>
        </tr>
        <tr>
            <th>助记码</th>
            <td><input name="mnemonicCode" class="easyui-textbox" data-options="validType:'length[0,100]',prompt:'通常为拼音简码...'" /></td>
            <th>类别</th>
            <td>
                <input name="categoryId" />
            </td>
            <th>品牌</th>
            <td>
                <input name="brandId" />
            </td>
        </tr>
        <tr>
            <th>单位</th>
            <td>
                <input name="unitId" />
            </td>
            <th></th>
            <td>
            </td>
            <th></th>
            <td></td>
        </tr>
        <tr>
            <th>原价</th>
            <td><input name="oldPrice" class="easyui-numberspinner" data-options="prefix:'￥',precision:2,value:0,min:0" /></td>
            <th>现价</th>
            <td><input name="price" class="easyui-numberspinner" data-options="required:true,prefix:'￥',precision:2,value:0,min:0" /></td>
            <th>积分</th>
            <td><input name="integral" class="easyui-numberspinner" data-options="value:0,min:0" /></td>
        </tr>
        <tr>
            <th class="top">属性组合sku</th>
            <td colspan="5" style=" padding:7px 0;">
                <table id="frmBXJGShopProductSku" style="width:100%;max-height:300px;"></table>
            </td>
        </tr>
        <tr>
            <th>焦点</th>
            <td colspan="5">
                <input class="easyui-checkbox" name="focus" value="true" label="焦点" />
                <input class="easyui-checkbox" name="hot" value="true" label="热卖" />
                <input class="easyui-checkbox" name="new" value="true" label="新品" />
                <input class="easyui-checkbox" name="home" value="true" label="首页显示" />
            </td>
        </tr>
        <tr>
            <th>发布</th>
            <td><input class="easyui-checkbox" name="published" data-options="value:true"></td>
            <th>发布开始时间</th>
            <td><input class="easyui-datetimebox" name="availableStart" data-options="showSeconds1:false"></td>
            <th>发布结束时间</th>
            <td><input class="easyui-datetimebox" name="availableEnd" data-options="showSeconds1:true"></td>
        </tr>
        <tr>
            <th class="top">图片</th>
            <td colspan="5" id="frmBXJGShopProductUploader" class="imgUploader-container" style=" padding:7px 0;">
                <div id="frmBXJGShopProductUploaderPicker" class="imgUploader-picker">选择图片</div>
                <div class="imgUploader-images" style="max-width:830px;">
                    <!--图片预览区，支持拖拽、截图粘贴...
                    <div class="imgUploader-img-container">
                        <a href="javascript:void(0);">×</a>
                        <img src="http://demo.dtcms.net/upload/201504/20/thumb_201504200119256512.jpg" />
                        <i class="imgUploader-img-success">上传完成</i>
                    </div>-->
                </div>
            </td>
        </tr>
        <tr>
            <th>简短描述</th>
            <td colspan="5"><input name="descriptionShort" class="easyui-textbox" data-options="width:820, validType:'length[1,100]',prompt:'显示在标题下方的商品简短描述信息...'" /></td>
        </tr>
        <tr>
            <th class="top">详细描述</th>
            <td colspan="5" style="padding-top:7px; ">
                <div id="bxjgShopProductEditor0" style="border: 1px solid #ddd;"></div>
                <div id="bxjgShopProductEditor" style="width:820px; height:600px;border: 1px solid #ddd;"></div>
            </td>
        </tr>
    </table>
</form>
<script>

    (function () {
        const m = 'BXJGShopProduct';
        const $dlg = $('#dlg' + m);
        const $frm = $dlg.find('form');
        const id = $dlg.data('id');
        const $name = $frm.find('[name="title"]');
        const $mnemonicCode = $frm.find('[name="mnemonicCode"]');
        const $cls = $frm.find('[name="categoryId"]');
        const $brand = $frm.find('[name="brandId"]');
        const $unit = $frm.find('[name="unitId"]');
        const $uploader = $('#frmBXJGShopProductUploader');
        const $uploaderImages = $uploader.find('.imgUploader-images');
        const $dgSku = $frm.find('#frmBXJGShopProductSku');
        //let attachment = $frm.find('.attachment');

        let initClsTask = $.Deferred();
        $cls.combotree({
            required: true,
            url: abp.appPath + 'api/services/BXJGShop/productcategory/GettreeForSelect',
            queryParams: { forType: 4 },
            onLoadSuccess: function (node, data) {
                initClsTask.resolve();
            },
            //不要用onChange，当选择空时文本框中会显示null
            onSelect: function (node) {
                if (!node.id) {
                    renderDynamicProperty([]);
                    return;
                }

                //若是新增模式
                //修改模式禁用了类别选择下拉框，所以可以不判断
                //if (!id) {
                abp.services.bxjgshop.productCategory.getDynamicProperty(node.id).done(function (r) {
                    renderDynamicProperty(r);
                });
                //}
            }
        });
        //新增或者修改模式动态渲染sku时都会用到
        function buildColumns() {
            return [
                { field: 'id', title: 'skuId', width: 10, hidden: true },
                //这里将被插入动态属性
                {
                    field: 'oldPrice',
                    title: '原价',
                    width: 100,
                    align: 'right',
                    formatter: val => val ? '￥' + parseFloat(val).toFixed(2) : '',
                    editor: {
                        type: 'numberspinner',
                        options: {
                            precision: 2,
                            prefix: '￥',
                            min: 0
                        }
                    }
                },
                {
                    field: 'price',
                    title: '现价',
                    width: 100,
                    align: 'right',
                    formatter: val => val ? '￥' + parseFloat(val).toFixed(2) : '',
                    editor: {
                        type: 'numberspinner',
                        options: {
                            precision: 2,
                            prefix: '￥',
                            min: 0
                        }
                    }
                },
                {
                    field: 'integral',
                    title: '积分',
                    width: 100,
                    align: 'right', editor: {
                        type: 'numberspinner',
                        options: {
                            min: 0
                        }
                    }
                }
            ];
        }
        //新增模式渲染sku动态属性
        function renderDynamicProperty(data) {
            /*
             * 所有列必须设置宽度，否则重新渲染时会报错
             * 使大量行进入编辑模式时会很卡，所以最好是值保持一个行进入编辑状态
             * datagrid中的combobox结束编辑时显示的是value，需要使用dagagrid列的formatter来自己处理
             */

            //首次调用会异常，目的是清空数据方便渲染
            try {
                $dgSku.datagrid('loadData', []);
            } catch { }

            let columns = buildColumns();

            if (data && data.length > 0) {

                //便利商品分类允许的sku动态属性列表，以生成sku界面列
                data.forEach(function (curr, index, ary) {

                    //定义dagagrid中的一个sku动态属性列
                    let column = {
                        field: 'dynamicProperty' + (index + 1) + 'Value',
                        title: curr.displayName,
                        width: 100,
                        align: 'center'
                    };
                    let columnText = { field: 'dynamicProperty' + (index + 1) + 'Text', hidden: true };
                    //初始化此列的编辑器
                    if (curr.inputType == "COMBOBOX") {
                        let sj = new Array();       //定义下拉框中的数据
                        //为下拉框填充数据
                        for (let i in curr.dynamicPropertyValues) {
                            sj.push({ value: i, displayText: curr.dynamicPropertyValues[i] });
                        }
                        //构造列的其它属性
                        column.editor = {
                            type: 'combobox',
                            options: {
                                editable: false,
                                data: sj,
                                onSelect: function (record) {
                                    let row = $dgSku.datagrid('getSelected');
                                    row[columnText.field] = record.displayText;
                                }
                            }
                        };
                        //默认情况下结束编辑时显示的value
                        column.formatter = function (value, row, idx) {
                            //for (let i = 0; i < sj.length; i++) {
                            //    let item = sj[i];
                            //    if (item.value == value) {
                            //        return item.displayText;
                            //    }
                            //}
                            return row[columnText.field];
                        };
                    } else if (curr.inputType == "CHECKBOX") {
                        column.editor = {
                            type: 'checkbox',
                            options: {
                                on: "√",
                                off: "×",
                                onChange: function (checked) {
                                    let row = $dgSku.datagrid('getSelected');
                                    row[columnText.field] = checked ? '√' : '×';
                                }
                            }
                        };
                    } else {
                        column.editor = {
                            type: 'textbox',
                            onChange: function (newValue, oldValue) {
                                let row = $dgSku.datagrid('getSelected');
                                row[columnText.field] = newValue;
                            }
                        };
                    }
                    columns.splice(index + 1, 0, column);
                    columns.splice(index + 2, 0, { field: 'dynamicProperty' + (index + 1) + 'Id', hidden: true });
                    columns.splice(index + 3, 0, { field: 'dynamicProperty' + (index + 1) + 'Name', hidden: true });
                    columns.splice(index + 4, 0, columnText);
                    columns.splice(index + 5, 0, { field: 'dynamicProperty' + (index + 1) + 'DisplayName', hidden: true });
                });
            }
            $dgSku.datagrid({
                singleSelect: true,
                columns: [columns],
                onLoadSuccess: function (d) {
                    //启用编辑的行太多时非常卡，即使用线程也非常不方便
                    //for (let i = 10; i < data.length; i++) {
                    //  $dgSku.datagrid('beginEdit', i);
                    //}
                    if (d && d.rows && d.rows.length > 0)
                        $(this).datagrid('selectRow', 0);
                },
                onSelect: function (index, row) {
                    let rows = $(this).datagrid('getRows');
                    for (let i = 0; i < rows.length; i++) {
                        $(this).datagrid('endEdit', i);
                    }
                    $(this).datagrid('beginEdit', index);
                }
            });
            if (!data || data.length == 0)
                return;
            let rows = [];
            for (let i = 0; i < 50; i++) {
                let row = {
                    oldPrice: 0,
                    price: 0,
                    integral: 0
                };
                data.forEach(function (curr, index, ary) {
                    row['dynamicProperty' + (index + 1) + 'Id'] = curr.id;
                    row['dynamicProperty' + (index + 1) + 'Name'] = curr.propertyName;
                    row['dynamicProperty' + (index + 1) + 'DisplayName'] = curr.displayName;
                });
                rows.push(row);
            }
            $dgSku.datagrid('loadData', rows);
        }
        //修改模式渲染sku动态属性
        function renderDynamicProperty1(data) {

            $cls.combotree('readonly');

            let columns = buildColumns();

            for (let i = 0; i < 5; i++) {
                let pname = 'dynamicProperty' + i + 'Id';
                let row;
                for (let k = 0; k < data.length; k++) {
                    let curr = data[k];
                    if (curr[pname]) {
                        row = curr;
                        break;
                    }
                }
                if (!row)
                    continue;

                columns.splice(i, 0, { field: pname, hidden: true });
                columns.splice(i, 0, { field: 'dynamicProperty' + i + 'Name', hidden: true });
                columns.splice(i, 0, { field: 'dynamicProperty' + i + 'DisplayName', hidden: true });
                columns.splice(i, 0, { field: 'dynamicProperty' + i + 'Value', hidden: true });
                columns.splice(i, 0, { field: 'dynamicProperty' + i + 'Text', title: row['dynamicProperty' + i + 'DisplayName'], width: 100 });
            }

            $dgSku.datagrid({
                singleSelect: true,
                columns: [columns],
                onLoadSuccess: function (d) {
                    if (d && d.rows && d.rows.length > 0)
                        $(this).datagrid('selectRow', 0);
                },
                onSelect: function (index, row) {
                    let rows = $(this).datagrid('getRows');
                    for (let i = 0; i < rows.length; i++) {
                        $(this).datagrid('endEdit', i);
                    }
                    $(this).datagrid('beginEdit', index);
                }
            });

            $dgSku.datagrid('loadData', data);
        }

        let initBrandTask = $.Deferred();
        $brand.combobox({
            editable: false,
            url: abp.appPath + 'api/services/app/GeneralTree/GetNodesForSelect',
            queryParams: { forType: 4, ParentId: abp.setting.get('DataDictionayMigrationValuepinpai') },
            onLoadSuccess: function () {
                initBrandTask.resolve();
            }
        });

        let initUnitTask = $.Deferred();
        $unit.combobox({
            editable: false,
            url: abp.appPath + 'api/services/app/GeneralTree/GetNodesForSelect',
            queryParams: { forType: 4, ParentId: abp.setting.get('DataDictionayMigrationValuedanwei') },
            onLoadSuccess: function () {
                initUnitTask.resolve();
            }
        });

        $dlg.data('clickSave', function () {

            //验证录入
            if (!$frm.form('validate'))
                return;

            //封面图
            var files = uploader.getFiles('complete');
            if (!files || files.length == 0) {
                abp.message.error('请至少上传一张封面图');
                return;
            }

            //处理简单的表单数据
            var postData = $frm.serializeJSON();


            //处理sku
            let rows = $dgSku.datagrid('getRows');
            for (let i = 0; i < rows.length; i++) {
                $dgSku.datagrid('endEdit', i);
            }
            let tempSkuRows = $dgSku.datagrid('getData').rows;
            postData.skus = [];
            tempSkuRows.forEach(function (curr, idx, ary) {
                for (let i = 0; i < 5; i++) {
                    if (curr['dynamicProperty' + i + 'Value'] && curr['dynamicProperty' + i + 'Value'] != '×') {
                        postData.skus.push(curr);
                        break;
                    }
                }
            });

            //处理商品图片
            postData.images = new Array();
            files.forEach(function (currentValue, index, arr) {
                postData.images.push(currentValue.serverPath);
            });

            //html编辑器中的完整描述
            postData.descriptionFull = editor.txt.html();


            let defer;
            if (id) {
                defer = abp.services.bxjgshop.product.update(postData).done(function (d) {
                    abp.notify.success(abp.localization.bxjgUtils('修改') + abp.localization.bxjgUtils('成功') + '!');
                    onSaved('onUpdated');
                });
            } else {
                defer = abp.services.bxjgshop.product.create(postData).done(function (d) {
                    abp.notify.success(abp.localization.bxjgUtils('新增') + abp.localization.bxjgUtils('修改') + '!');
                    onSaved('onAdded');
                });
            }
            abp.ui.setBusy($dlg, defer);
        });

        function onSaved(funcName) {
            var f = $dlg.data(funcName);
            if (f)
                f();
        }

        //图片上传开始-------------------------------------
        let uploader = WebUploader.create({

            // 选完文件后，是否自动上传。
            auto: true,

            // swf文件路径
            swf: '/lib/webuploader-0.1.5/Uploader.swf',

            // 文件接收服务端。
            server: abp.appPath + 'api/file/upload',

            // 选择文件的按钮。可选。
            // 内部根据当前运行是创建，可能是input元素，也可能是flash.
            pick: '#frmBXJGShopProductUploaderPicker',

            // 只允许选择图片文件。
            accept: {
                title: 'Images',
                extensions: 'gif,jpg,jpeg,bmp,png',
                mimeTypes: 'image/*'
            }
        });
        uploader.on('uploadSuccess', function (file, response) {
            file.serverPath = response.result[0].filePath;
            file.thumPath = response.result[0].thumPath;
        });
        uploader.on('fileQueued', function (file) {
            file.on('statuschange', function (n, o) {
                $i.removeClass('imgUploader-img-' + o);
                $i.addClass('imgUploader-img-' + n);
                let statusText = '';
                switch (n) {
                    case 'complete':
                        statusText = '已完成';
                        break;
                    case 'error':
                        statusText = '失败';
                        break;
                    case 'progress':
                        statusText = '上传中...';
                        break;
                    default:
                        statusText = file.statusText;
                }
                $i.text(statusText);
            });


            let $box = $('<div class="imgUploader-img-container">').appendTo($uploaderImages);
            let $a = $('<a>×</a>').appendTo($box);
            let $img = $('<img />').appendTo($box);
            let $i = $('<i />').appendTo($box);


            $a.on('click', function () {
                uploader.removeFile(file, true);
                $box.remove();
            });
            if (file.thumPath) {
                $img.attr('src', abp.appPath + file.thumPath);
                file.setStatus('complete');
            } else {
                uploader.makeThumb(file, function (error, src) {
                    if (error) {
                        $img.replaceWith('<span>不能预览</span>');
                        return;
                    }
                    $img.attr('src', src);
                });
            }
        });
        uploader.on('uploadBeforeSend', function (obj, data, headers) {
            headers.Authorization = "Bearer " + abp.getCurrentJWTToken();
            headers.createThum = true;
        });
        //图片上传结束-------------------------------------

        //富文本编辑器开始---------------------------------
        var E = window.wangEditor
        var editor = new E('#bxjgShopProductEditor0', '#bxjgShopProductEditor')
        // 或者 var editor = new E( document.getElementById('editor') )

        //editor.customConfig.uploadImgShowBase64 = false;
        editor.create();
        editor.config.customUploadImg = function (resultFiles, insertImgFn) {
            // resultFiles 是 input 中选中的文件列表
            // insertImgFn 是获取图片 url 后，插入到编辑器的方法
            var formData = new FormData();
            resultFiles.forEach(function (item, index, ary) {
                formData.append("file", item);
            });
            abp.ajax({
                url: abp.appPath + 'api/file/upload',
                type: 'post',
                data: formData,
                contentType: false,
                processData: false,
                success: function (res) {
                    insertImgFn(res[0].fileUrl);
                }
            });
            // 上传图片，返回结果，将图片插入到编辑器中
            //insertImgFn(imgUrl)
        };
        //富文本编辑器结束---------------------------------


        setTimeout(function () {
            $name.next('span').find('input').focus();
            var $realName = $frm.find('[name="title"]').prev();  //这里必须直接通过jquery做选择
            $realName.focus().blur(function () {
                var input = $name.val();
                if (!input)
                    return;
                if ($mnemonicCode.val())
                    return;
                abp.services.app.utils.getPinYinFirstLetter(input).done(function (d) {
                    $mnemonicCode.textbox('setValue', d);
                });
            });



            if (id) {
                let initFormTask = abp.services.bxjgshop.product.get({ id: id }).done(function (d) {
                    $frm.form('load', d);
                    //异步加载本来就在另一个线程，所以这里也许没必要再开线程来等待ui先渲染
                    renderDynamicProperty1(d.skus);
                    //图像初始化
                    if (d.images) {
                        d.images.forEach(function (item, index) {
                            var obj = {
                                id: item.thumPath,//这个好像也没什么卵用
                                name: item.thumPath,
                                //ext: item.extension.substring(1),//这行貌似没什么卵用，webuploader取文件名后缀
                                size: 1
                            };
                            var file = new WebUploader.File(obj);
                            file.serverPath = item.filePath;
                            file.thumPath = item.thumPath;
                            uploader.addFiles(file);
                            file.setStatus('complete');
                        });
                    }

                    //商品完整描述初始化
                    editor.txt.html(d.descriptionFull);
                });
                abp.ui.setBusy($dlg, $.when(initFormTask, initClsTask, initBrandTask, initUnitTask));
            } else {
                abp.ui.setBusy($dlg, $.when(initBrandTask, initUnitTask, initClsTask.done(function () {
                    let tree = $cls.combotree('tree');
                    $cls.combotree('setValue', $dlg.data('clsId'));
                    var node = tree.tree('find', $dlg.data('clsId'));
                    tree.tree('select', node.target);
                    //$cls.val($dlg.data('clsId'));//经过测试这样无效
                })));
            }
        }, 0);
    })();
</script>
